package com.multi.thread.chapter04.demo13;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class TestReadWriteLock {
	
	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
	
	public void read() {
		try {
			lock.readLock().lock();
			System.out.println("获取读锁：" + Thread.currentThread().getName() + ", " + System.currentTimeMillis());
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.readLock().unlock();
		}
	}
	
	public void write() {
		try {
			lock.writeLock().lock();
			System.out.println("获取写锁：" + Thread.currentThread().getName() + ", " + System.currentTimeMillis());
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.writeLock().unlock();
		}
	}
	
	class ThreadA extends Thread {
		private TestReadWriteLock service = new TestReadWriteLock();

		public ThreadA(TestReadWriteLock service) {
			this.service = service;
		}
		
		@Override
		public void run() {
			service.read();
		}
		
	}
	
	class ThreadB extends Thread {
		private TestReadWriteLock service = new TestReadWriteLock();

		public ThreadB(TestReadWriteLock service) {
			this.service = service;
		}
		
		@Override
		public void run() {
			service.write();
		}
		
	}

	public static void main(String[] args) throws InterruptedException {
		final TestReadWriteLock service = new  TestReadWriteLock();
		ThreadA a = new TestReadWriteLock().new ThreadA(service);
		a.setName("A");
		a.start();
		
		Thread.sleep(1000);
		
		ThreadB b = new TestReadWriteLock().new ThreadB(service);
		b.setName("B");
		b.start();
	}
}
